"""
运行所有测试脚本
"""
import sys
import os
import time
import traceback
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def run_test(test_name, test_function):
    """运行单个测试"""
    print(f"\n{'='*60}")
    print(f"🧪 运行测试: {test_name}")
    print(f"{'='*60}")
    
    start_time = time.time()
    try:
        test_function()
        end_time = time.time()
        print(f"\n✅ {test_name} 测试成功完成 (用时: {end_time - start_time:.2f}秒)")
        return True
    except Exception as e:
        end_time = time.time()
        print(f"\n❌ {test_name} 测试失败 (用时: {end_time - start_time:.2f}秒)")
        print(f"错误信息: {str(e)}")
        print(f"详细错误:")
        traceback.print_exc()
        return False

def main():
    """运行所有测试"""
    print("🚀 开始运行所有测试脚本")
    print(f"测试时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 测试列表 (按重要性和依赖关系排序)
    tests = [
        # 1. 基础功能测试
        ("基础模块测试", lambda: exec(open("tests/test_modules.py").read())),
        
        # 2. 输入归一化测试
        ("输入归一化测试", lambda: exec(open("tests/test_input_normalization.py").read())),
        
        # 3. 数据加载测试
        ("修复数据加载器测试", lambda: exec(open("tests/test_fixed_data_loader.py").read())),
        ("滑动窗口测试", lambda: exec(open("tests/test_sliding_window.py").read())),
        ("不同滑动步长测试", lambda: exec(open("tests/test_different_sliding_steps.py").read())),
        
        # 4. 训练优化测试
        ("随机批次选择测试", lambda: exec(open("tests/test_random_batch_selection.py").read())),
        
        # 5. 系统集成测试
        ("完整系统测试", lambda: exec(open("tests/test_complete_system.py").read())),
        ("滑动窗口系统测试", lambda: exec(open("tests/test_sliding_system.py").read())),
        ("最终系统测试", lambda: exec(open("tests/test_final_system.py").read())),
    ]
    
    # 运行测试统计
    total_tests = len(tests)
    passed_tests = 0
    failed_tests = 0
    test_results = []
    
    overall_start_time = time.time()
    
    # 逐个运行测试
    for test_name, test_func in tests:
        try:
            success = run_test(test_name, test_func)
            if success:
                passed_tests += 1
                test_results.append((test_name, "✅ 通过"))
            else:
                failed_tests += 1
                test_results.append((test_name, "❌ 失败"))
        except Exception as e:
            failed_tests += 1
            test_results.append((test_name, f"❌ 异常: {str(e)}"))
            print(f"运行 {test_name} 时发生异常: {e}")
    
    overall_end_time = time.time()
    total_time = overall_end_time - overall_start_time
    
    # 打印测试总结
    print(f"\n{'='*80}")
    print(f"📊 测试总结报告")
    print(f"{'='*80}")
    print(f"总测试数量: {total_tests}")
    print(f"通过测试: {passed_tests}")
    print(f"失败测试: {failed_tests}")
    print(f"成功率: {passed_tests/total_tests*100:.1f}%")
    print(f"总用时: {total_time:.2f}秒")
    
    print(f"\n📋 详细结果:")
    for i, (test_name, result) in enumerate(test_results, 1):
        print(f"  {i:2d}. {test_name:<30} {result}")
    
    # 根据结果给出建议
    if failed_tests == 0:
        print(f"\n🎉 所有测试都通过了！系统运行正常。")
    elif failed_tests <= 2:
        print(f"\n⚠️  有少量测试失败，建议检查失败的测试项目。")
    else:
        print(f"\n🚨 多个测试失败，建议仔细检查系统配置和代码。")
    
    print(f"\n💡 建议:")
    print(f"  1. 查看失败测试的详细错误信息")
    print(f"  2. 检查数据文件是否存在")
    print(f"  3. 验证模型配置参数")
    print(f"  4. 确认依赖库版本")
    
    return passed_tests, failed_tests

def run_quick_tests():
    """运行快速测试 (跳过耗时的系统测试)"""
    print("⚡ 运行快速测试模式")
    
    quick_tests = [
        ("基础模块测试", lambda: exec(open("tests/test_modules.py").read())),
        ("输入归一化测试", lambda: exec(open("tests/test_input_normalization.py").read())),
        ("修复数据加载器测试", lambda: exec(open("tests/test_fixed_data_loader.py").read())),
        ("随机批次选择测试", lambda: exec(open("tests/test_random_batch_selection.py").read())),
    ]
    
    passed = 0
    for test_name, test_func in quick_tests:
        if run_test(test_name, test_func):
            passed += 1
    
    print(f"\n⚡ 快速测试完成: {passed}/{len(quick_tests)} 通过")
    return passed, len(quick_tests) - passed

def check_test_environment():
    """检查测试环境"""
    print("🔍 检查测试环境...")
    
    # 检查必要的文件
    required_files = [
        "config.py",
        "model_definitions.py", 
        "data_loader.py",
        "utils.py",
        "trainer.py"
    ]
    
    missing_files = []
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)
    
    if missing_files:
        print(f"❌ 缺少必要文件: {missing_files}")
        return False
    
    # 检查数据目录
    if not os.path.exists("data"):
        print("⚠️  数据目录不存在，某些测试可能失败")
    
    print("✅ 测试环境检查完成")
    return True

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="运行测试脚本")
    parser.add_argument("--quick", action="store_true", help="运行快速测试")
    parser.add_argument("--check", action="store_true", help="只检查环境")
    
    args = parser.parse_args()
    
    if args.check:
        check_test_environment()
    elif args.quick:
        check_test_environment()
        run_quick_tests()
    else:
        check_test_environment()
        main() 